import { React, useEffect, useState } from 'react';
import './mynews.css';
import '../../../index.css';
import axios from 'axios';
import { useNavigate } from 'react-router-dom';
import InterIP from '../../../IP/IP'
export default function Mynews() {

    const navigate = useNavigate();
    const [mynewsArr, setMynewsArr] = useState([]);
    let IP = InterIP().props.children;

    //接收数据
    useEffect(() => {
        var userID = document.cookie.slice(5);
        let IP = InterIP().props.children;
        axios.post("http://" + IP + ":3000/user/news", {
            user_id: userID,
        })
            .then((res) => {
                setMynewsArr((mynewsArr) => mynewsArr = res.data)
            })
    }, [])

    //删除
    function shanchu(id) {
        return () => {
            console.log(id);
            axios.post("http://" + IP + ":3000/user/delNews", {
                message_id: id,
            })
                .then((res) => {
                    console.log(res);
                })
        }
    }

    //向详情页传参
    function chakan(data) {
        return () => {
            axios.post("http://" + IP + ":3000/user/selNews", {
                message_id: data.message_id,
            })
                .then((res) => {
                    console.log(res);
                })

            navigate('/home/person/detnews', {
                state: {
                    data: data,
                }
            });
        }
    }


    return (
        <div id="myNews">
            <div className="mybill_top">我的消息</div>
            <div className="mynews_main">
                <table cellSpacing="0">
                    <thead>
                        <tr>
                            <th>标题</th>
                            <th>发送时间</th>
                            <th>状态</th>
                            <th>操作</th>
                        </tr>
                    </thead>
                    <tbody>
                        {mynewsArr.map((data) => {
                            return (
                                <tr key={data.message_id}>
                                    <td>{data.message_text}</td>
                                    <td>{data.message_time}</td>
                                    <td>{data.message_status}</td>
                                    <td>
                                        <button onClick={chakan(data)}>查看</button>
                                        <button onClick={shanchu(data.message_id)}>删除</button>
                                    </td>
                                </tr>
                            )
                        })}

                    </tbody>
                </table>
            </div>
        </div>
    )
}
